package lambda_expression;

import com.alibaba.fastjson.JSON;

import java.util.*;
import java.util.function.Supplier;

/**
 * Lambda表达式方法引用
 * 1. 静态方法引用
 *      类型名称.方法名称() --> 类型名称::方法名
 * 2. 实例方法引用
 *      创建类型对应的一个对象 --> 对象应用::实例方法名
 * 3. 构造方法引用
 */
public class App5 {

    public static void main(String[] args) {

        List<Person> personList = new ArrayList<Person>(){
            {
                add(new Person("bom", "男", 45));
                add(new Person("atom", "女", 15));
                add(new Person("zero", "男", 23));
                add(new Person("creo", "女", 21));
            }
        };

        // 匿名内部类形式
        Collections.sort(personList, new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                return o1.getAge() - o2.getAge();
            }
        });

        System.out.println(JSON.toJSONString(personList, true));

        // Lambda表达式形式
        Collections.sort(personList,(p1,p2) -> p1.getAge() - p2.getAge() );

        System.out.println(JSON.toJSONString(personList, true));

        // ================方法引用形式(静态方法引用)================
        Collections.sort(personList, Person::compareByAge);

        System.out.println(JSON.toJSONString(personList, true));

        // ================方法引用形式(实例方法引用)================
        PersonUtil pu = new PersonUtil();
        Collections.sort(personList, pu::compareByName);

        System.out.println(JSON.toJSONString(personList, true));

        // ================方法引用形式(构造方法引用)================
        IPerson person = Person::new;
        Person p = person.initPerson("张飞", "男", 65);
        System.out.println(JSON.toJSONString(p, true));
    }



}

class PersonUtil{
    public int compareByName(Person p1, Person p2){

        return p1.getName().hashCode() - p2.getName().hashCode();
    }
}

interface IPerson{
    Person initPerson(String name, String gender, int age);
}



class Person {
    private String name;
    private String gender;
    private int age;

    public static int compareByAge(Person p1, Person p2){
        return p1.age - p2.age;
    }

    public Person(){}

    public Person(String name, String gender, int age) {
        this.name = name;
        this.gender = gender;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
